import os
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import tkinter as tk
from tkinter import scrolledtext
from tkinter import messagebox
import jieba
import re
import requests
from bs4 import BeautifulSoup
import time
from selenium import webdriver
from selenium.webdriver.edge.service import Service



class SearchEngineGUI:  # GUI界面
    def __init__(self):

        root = tk.Tk()
        self.root = root
        root.title("Yummy Engine")
        self.root.geometry("800x500+1100+500")
        #
        menu = tk.Menu(root)
        root.config(menu=menu)
        menu.add_command(label="Exit", command=root.destroy)
        file_menu = tk.Menu(menu)
        menu.add_command(label="About", command=self.about)
        menu.add_command(label="findmore", command=self.findmore)
        menu.add_command(label="browser",command=self.browser)
        #
        self.search_query_label = tk.Label(self.root, text="检索内容: ")
        self.search_query_label.pack()
        self.search_query_entry = tk.Entry(self.root, width=50)
        self.search_query_entry.pack()

        self.folder_path_label = tk.Label(self.root, text="文件夹路径:")
        self.folder_path_label.pack()
        self.folder_path_entry = tk.Entry(self.root, width=50)
        self.folder_path_entry.pack()

        self.file_path_label = tk.Label(self.root, text="目标文件路径:")
        self.file_path_label.pack()
        self.file_path_entry = tk.Entry(self.root, width=50)
        self.file_path_entry.pack()
        self.search_button = tk.Button(self.root,
                                       text="检索",
                                       command=self.search)
        self.search_button.pack()
        self.results_path = scrolledtext.ScrolledText(self.root, width=90, height=10)
        self.results_path.pack()
        self.open_button = tk.Button(self.root,
                                     text="打开",
                                     command=self.open)
        self.open_button.pack()
        self.results_text = scrolledtext.ScrolledText(self.root, width=90, height=25)
        self.results_text.pack()

    def read_files(self, folder_path):
        texts = {}
        for filename in os.listdir(folder_path):
            if filename.endswith(".txt"):
                with open(os.path.join(folder_path, filename), 'r', encoding='utf-8') as file:
                    content = file.read()
                    texts[filename]=content
        return texts

    def tokenize_text(self, texts):
        b=[]
        for text in texts.values():
            a=[]
            if text.isalpha():
                a.append(word_tokenize(text))
                b.append(a)
            else:
                a.append((jieba.lcut(text)))
                b.append(a)
        tokenized_texts = dict(zip(texts.keys(), b))
        return tokenized_texts

    # 2. 构建词典
    def dictionary(self, tokenized_texts):
        dictionary=tokenized_texts
        stop_words = set(stopwords.words('english'))
        stopwords_path = "D:\\code\停用词.txt"
        with open(stopwords_path, 'r', encoding='utf-8') as file:
            for line in file:
                stop_words.add(line.strip())
        # 停用词列表
        for text in dictionary.values():
            for words in text:
                #for word in words:
                    i = 0
                    while i < len(words):
                        if words[i] in stop_words:
                            # 找到停用词，然后删除它
                            words.pop(i)
                        else:
                            i += 1  # 如果不是停用词，继续检查下一个词


        print(dictionary)
        print(stop_words)
        return dictionary


    def search(self):
        global file_path
        folder_path = self.folder_path_entry.get()
        query = self.search_query_entry.get()

        if not folder_path or not query:
            self.results_path.delete(1.0, tk.END)
            self.results_path.insert(tk.END, "请提供文件夹路径和检索内容。")
            return

        texts = self.read_files(folder_path)#texts是列表
        tokenized_texts = self.tokenize_text(texts)
        dictionary = self.dictionary(tokenized_texts)

        results = []
        file_names = []
        for key, value in dictionary.items():
            for words in value:
                for word in words:
                    if query in word:
                        file_names.append(key)
        file_names1=set(file_names)

        for file_name in file_names1:
            file_path =os.path.join(folder_path,file_name)  # 拼接文件路径
            results.append(file_path)  # 添加匹配结果
        self.results_path.delete(1.0, tk.END)
        print(results)

        if results:
            for result in results:
                file_path = result
                self.results_path.insert(tk.END, f"文件:{file_path}\n")
            return file_path
        else:
            self.results_path.insert(tk.END, "未找到匹配项。")

    def open(self):
        s = self.file_path_entry.get()
        if s:
            pattern = r'.*?txt.*'
            match = re.search(pattern, s)
            if match:
                result_file_path = match.group()
            with open(result_file_path, 'r',
                      encoding='utf-8') as f:
                result_file_content = f.read()
            self.results_text.delete(1.0, tk.END)
            self.results_text.insert(tk.END, result_file_content+"\n\n\n粘贴链接到右上方browser里可了解更多哦")
        else:
            self.results_text.delete(1.0, tk.END)
            self.results_text.insert(tk.END, "请输入目标文件名到指定区域。")

    def about(self):
        messagebox.showinfo("about", "可实现功能：根据输入内容查找文件，自动过滤部分无意义词汇。\n祝您使用愉快！")

    def findmore(self):
        findmore = tk.Toplevel(self.root)
        findmore.title("探寻新美食")
        findmore.geometry("400x300+0+0")

        findmore_entry = tk.Entry(findmore)
        findmore_entry.pack()

        menu = tk.Menu(findmore)
        findmore.config(menu=menu)
        menu.add_command(label="exit", command=findmore.destroy)

        findmore_button = tk.Button(findmore, text="寻找新美食", command=lambda: self.xiachufang(findmore_entry.get()))
        #findmore_button = tk.Button(findmore, text="寻找新美食", command=self.xiachufang)  # 修改这里
        findmore_button.pack()
        keyword = findmore_entry.get()
        return keyword
    #改成全局
    def browser(self):#调整输入框尺寸
        browser = tk.Toplevel(self.root)
        browser.title("browser——了解更多")
        browser.geometry("400x300+0+0")

        menu = tk.Menu(browser)
        browser.config(menu=menu)
        menu.add_command(label="exit", command=browser.destroy)
        menu.add_command(label="close_browser", command=self.browser_close)


        browser_entry = tk.Entry(browser)
        browser_entry.pack()

        browser_button = tk.Button(browser, text="搜索", command=lambda: self.browser_open(browser_entry.get()))
        # browser_button = tk.Button(browser, text="寻找新美食", command=self.browser_open)  # 修改这里
        browser_button.pack()
        url = browser_entry.get()
        return url


    def xiachufang(self,keyword):
        keyword1=keyword
        foods_list = []
        # keyword=input("请输入你想吃的菜:")
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"}

        # 实现自动翻页
        for j in range(3):
            url = f"https://www.xiachufang.com/search/?keyword={keyword1}&page={j}"
            response = requests.get(url=url, headers=headers)

            # 存储食物数据

            soup = BeautifulSoup(response.text, 'html.parser')  # 解析数据
            inf = soup.find_all('div',
                                class_="recipe recipe-215-horizontal pure-g image-link display-block")  # 找到最小父级共同标签

            for food in inf:
                # t=1
                food_name = food.find('img')['alt']  # 菜名
                food_ingredients = food.find('p', class_='ing ellipsis').text  # 食材
                food_href = 'https://www.xiachufang.com/' + food.find('a')['href']  # 链接
                foods_list.append([food_name, food_href, food_ingredients])  # 把获取的数据添加到列表
                recipe_info = f"菜名：{food_name}\n用料：{food_ingredients}\n步骤链接：{food_href}"
                print(recipe_info)
                folder_path = "D:\code\pythonProject1\database\食谱"
                file_path = os.path.join(folder_path, f"{food_name}.txt")
                # t+=1
                with open(file_path, "w", encoding="utf-8") as file:
                    file.write(recipe_info)
                    file.close()
                    print(f"《{food_name}》菜谱已生成")

    def browser_open(self,url):
        service = Service(executable_path='D:\\edgedriver_win64 (1)\\msedgedriver.exe')

        browser = webdriver.Edge(service=service)
        url = url

        browser.maximize_window()
        browser.get(url=url)
        time.sleep(10000)
        return browser
    def browser_close(self,browser):
        browser=browser
        browser.close()


if __name__ == "__main__":
    a = SearchEngineGUI()
    a.root.mainloop()